package com.algo.generator.config;

import com.algo.generator.common.BaseResponse;
import com.algo.generator.constant.ResponseCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.List;

/**
 * 全局异常
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * MethodArgumentNotValidException
     * 参数异常拦截 (model 里面的)
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse methodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        StringBuilder sbMSG = new StringBuilder();
        List<ObjectError> errors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
        for (ObjectError oe : errors) {
            sbMSG.append(String.format(" | 字段[%s]-%s", ((FieldError) oe).getField(), oe.getDefaultMessage()));
        }
        logger.error(MessageFormat.format("接口:{0},异常信息:{1}", request.getServletPath(), e.getMessage()), e);
        return new BaseResponse<>(ResponseCodeEnum.INVALID_PARAMETER.getCode(), sbMSG.substring(3));
    }

    /**
     * 参数异常拦截
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ServletRequestBindingException.class)
    public BaseResponse servletRequestBindingException(ServletRequestBindingException e, HttpServletRequest request) {
        logger.error(MessageFormat.format("接口:{0},异常信息:{1}", request.getServletPath(), e.getMessage()), e);
        return new BaseResponse<>(ResponseCodeEnum.INVALID_PARAMETER.getCode(), e.getMessage());
    }

    /**
     * 参数异常拦截
     *
     * @param e
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public BaseResponse illegalArgument(IllegalArgumentException e) {
        logger.error(">>>>>> Illegal argument exception handler ->", e);
        return new BaseResponse(ResponseCodeEnum.FAIL);
    }

    /**
     * 全局异常
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(Exception.class)
    public BaseResponse errorException(Exception e, HttpServletRequest request) {
        logger.error(MessageFormat.format("接口:{0},异常信息:{1}", request.getServletPath(), e.getMessage()), e);
        return new BaseResponse<>(ResponseCodeEnum.FAIL);
    }

}
